﻿using AutoMapper;
using B.S.Sterilizationcenter.Domain.zmc;
using B.S.Sterilizationcenter.ErrorCode;
using B.S.Sterilizationcenter.Read.API.Appliaction.Commends.zmc;
using B.S.Sterilizationcenter.Read.API.Dto;
using MediatR;
using SqlSugar;

namespace B.S.Sterilizationcenter.Read.API.Appliaction.CommandHandlers.zmc
{
    public class QueryApparatusTypeTreeCommandHandlers : IRequestHandler<QueryApparatusTypeTreeCommand, ApiResult<List<ApparatusTypeDTO>>>
    {
        private readonly ISqlSugarClient db;
        private readonly IMapper mapper;

        public QueryApparatusTypeTreeCommandHandlers(ISqlSugarClient db, IMapper mapper)
        {
            this.db = db;
            this.mapper = mapper;
        }

        /// <summary>
        /// 查询器械分类树状结构
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<ApiResult<List<ApparatusTypeDTO>>> Handle(QueryApparatusTypeTreeCommand request, CancellationToken cancellationToken)
        {
            ApiResult<List<ApparatusTypeDTO>> result = new ApiResult<List<ApparatusTypeDTO>>();
            result.Code = ApiEnums.查询成功;
            result.Msg = "查询器械分类树状结构成功";
            result.Data = GetTree(0);
            return Task.FromResult(result);
        }

        public List<ApparatusTypeDTO> GetTree(int api)
        {
            var list = db.Queryable<ApparatusType>().Where(it => it.Aid == api).ToList();
            var res = new List<ApparatusTypeDTO>();
            foreach (var item in list)
            {
                var model = new ApparatusTypeDTO()
                {
                    value = item.ApparatusTypeId,
                    label = item.ApparatusTypeName,
                    children = GetTree(item.ApparatusTypeId)

                };
                res.Add(model);
            }
            return res;
        }
    }
}
